package com.sunwayhorizo.health.business.registries.organization.query;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;

import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.hl7.common.Hl7Exception;
import com.sunwayhorizo.health.hl7.persistent.RimCoreEntities;
import com.sunwayhorizo.health.hl7.rim.Organization;
import com.sunwayhorizo.health.hl7.rim.Role;
import com.sunwayhorizo.health.hl7.vocabulary.EntityCode;
import com.sunwayhorizo.health.hl7.vocabulary.RoleCode;

@Name("DepartmentQuery")
@Stateless
public class DepartmentQuery implements DepartmentQueryLocal {

    @PersistenceContext(unitName = "sunwayhealth")
    private EntityManager em;

    @Logger
    private Log log;
    
	@SuppressWarnings("unchecked")
    public List<Role> findWorkGroupAll() throws Hl7Exception
	{
	    StringBuilder jbql = new StringBuilder();
        jbql.append(" select r from Role r ");
        jbql.append(" left join r.roleIiList rii ");
        jbql.append(" where r.codeEtsId='" + RoleCode.WORKGROUP.toString()+ "' ");
        jbql.append(" and r.statusCode='0'");
        jbql.append(" order by rii.extensionTxt asc");
        List<Role> list = em.createQuery(jbql.toString()).getResultList();
        if(ListUtil.isNotEmpty(list)) return list;
        else return null;
	}
	
	@SuppressWarnings("unchecked")
    public List<Role> findOnlyDepartment(String orgId) throws Hl7Exception
	{
	        StringBuilder jbql = new StringBuilder();
	        jbql.append(" select r from Role r ");
	        jbql.append(" left join r.roleIiList rii ");
	        jbql.append(" where ( r.codeEtsId='" + RoleCode.DEPARTMENT.toString() + "' or r.codeEtsId='" + RoleCode.HOSPITAL.toString() + "')");
	        jbql.append(" and r.statusCode='0'");
	        jbql.append(" order by rii.extensionTxt asc");
	        List<Role> list = em.createQuery(jbql.toString()).getResultList();
	        return list;
	}
	
	@SuppressWarnings("unchecked")
    public List<Role> findDepartmentOrWorkGroupByOrgId(String orgId) throws Hl7Exception
	{
	    StringBuilder jbql = new StringBuilder();
	    jbql.append(" select r from Role r ");
	    jbql.append(" left join r.roleIiList rii ");
        jbql.append(" where ( r.codeEtsId='" + RoleCode.DEPARTMENT.toString() + "' or r.codeEtsId='" + RoleCode.HOSPITAL.toString()+ "' or r.codeEtsId='" + RoleCode.WORKGROUP.toString() + "')");
        jbql.append(" order by rii.extensionTxt asc");
        List<Role> list = em.createQuery(jbql.toString()).getResultList();
        return list;
	}
	
	@SuppressWarnings("unchecked")
    public List<Role> findActiveDeptOrWgByOrgId(String orgId) throws Hl7Exception
	{
	    StringBuilder jbql = new StringBuilder();
	    jbql.append(" select r from Role r ");
	    jbql.append(" left join r.roleIiList rii ");
        jbql.append(" where ( r.codeEtsId='" + RoleCode.DEPARTMENT.toString() + "' or r.codeEtsId='" + RoleCode.HOSPITAL.toString()+ "' or r.codeEtsId='" + RoleCode.WORKGROUP.toString() + "')");
        jbql.append(" and r.statusCode='0'");
        jbql.append(" order by rii.extensionTxt asc");
        List<Role> list = em.createQuery(jbql.toString()).getResultList();
        return list;
	}
	
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public List<Role> findListOrg(List orgIds) throws Hl7Exception
    {
        if (ListUtil.isEmpty(orgIds))  return null;
        StringBuilder jbql = new StringBuilder();
        jbql.append(" select r from Role r ");
        jbql.append("  where ");
        for (int i = 0; i < orgIds.size(); i++)
        {
            String id = (String) orgIds.get(i);
            if (i < orgIds.size() - 1)
            {
                jbql.append(" r.playerEntities.entityId=" + id + " or ");
            }
            else
            {
                jbql.append(" r.playerEntities.entityId=" + id);
            }
        }
        List<Role> listOrg = em.createQuery(jbql.toString()).getResultList();
        return listOrg;
    }
    
  
    @SuppressWarnings("unchecked")
    public Organization findOrganizationByCode(String code) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append(" select org from Organization org ");
        jbql.append(" left join ");
        jbql.append(" org.entyIiList ii where ii.extensionTxt='" + code + "'");
        List<Organization> list = em.createQuery(jbql.toString()).getResultList();
        if (ListUtil.isNotEmpty(list))
        {
            return (Organization) list.get(0);
        }
        return null;
    }
    
   
    @SuppressWarnings("unchecked")
    public List<Role> findRoleListByCond(String codingSchemesEnName, String conceptCode) throws Hl7Exception
    {
        if (StrUtil.isEmpty(codingSchemesEnName) && StrUtil.isEmpty(conceptCode))
            return null;
        StringBuilder jbql = new StringBuilder();
        jbql.append(" select r from Role r ");
        jbql.append(" left join ");
        jbql.append(" r.roleIiList rii ");
        jbql.append(" left join ");
        jbql.append(" r.roleCdSetsList cdSet ");
        jbql.append(" where r.codeEtsId='WORKGROUP' and r.statusCode='0' ");
        jbql.append(" and cdSet.codingschemeEnName=?1 and cdSet.conceptCode=?2 ");
        jbql.append(" order by rii.extensionTxt asc");
        Query query = em.createQuery(jbql.toString());
        query.setParameter(1, codingSchemesEnName);
        query.setParameter(2, conceptCode);
        List<Role> list = query.getResultList();
        if (ListUtil.isNotEmpty(list)) return list;
        return null;
    }
    
    @SuppressWarnings("unchecked")
    public List<Object> findWoroGroupIdsByDeptId(String deptId) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append(" select r.playerEntities.entityId from Role r ");
        jbql.append(" where r.codeEtsId='" + EntityCode.WORKGROUP.toString() + "' ");
        jbql.append(" and r.scoperEntities.entityId=" + deptId);
        List<Object> list = em.createQuery(jbql.toString()).getResultList();
        if (ListUtil.isNotEmpty(list))
            return list;
        return null;
    }
    
    @SuppressWarnings("unchecked")
    public Organization findDepartmentByCode(String code) throws Hl7Exception
    {

        StringBuilder jbql = new StringBuilder();
        jbql.append(" select r.playerEntities from Role r ");
        jbql.append(" left join ");
        jbql.append(" r.roleIiList rii");
        jbql.append(" where r.codeEtsId='"+ EntityCode.DEPARTMENT.toString() + "' and rii.extensionTxt='" + code + "' ");
        List<RimCoreEntities> list = em.createQuery(jbql.toString()).getResultList();
        if (ListUtil.isNotEmpty(list))
        {
            return (Organization) list.get(0);
        }
        return null;
    }
    
    @SuppressWarnings("unchecked")
    public Role findWorkGroupRoleByWorkGroupCode(String workGroupCode) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select r from Role r ");
        jpql.append(" left join ");
        jpql.append(" r.roleIiList ii ");
        jpql.append(" where ii.extensionTxt='");
        jpql.append(workGroupCode);
        jpql.append("'");
        List<Role> roles = em.createQuery(jpql.toString()).getResultList();
        if (ListUtil.isNotEmpty(roles))
        {
            return roles.get(0);
        }
        log.info("DepartmentManager-findWorkGroupRoleByWorkGroupCode-" + workGroupCode + "工作组找不到！");
        return null;
    }
    
   
    @SuppressWarnings("rawtypes")
    public boolean findDepartByDeptIds(List deptIds) throws Hl7Exception
    {
        List<Long> entyIdList = findEntityIdByRoleIds(deptIds);
        boolean b = false;
        if (ListUtil.isNotEmpty(entyIdList))
        {
            StringBuilder jpql = new StringBuilder();
            jpql.append(" select r.roleId from Role r ");
            jpql.append(" where r.codeEtsId='" + RoleCode.DEPARTMENT.toString() + "' and ( ");
            for (int i = 0; i < deptIds.size(); i++)
            {
                Long entyId = (Long) entyIdList.get(i);
                if (i < entyIdList.size() - 1)
                {
                    jpql.append(" r.scoperEntities.entityId=" + entyId + " or ");
                }
                else
                {
                    jpql.append(" r.scoperEntities.entityId=" + entyId);
                }
            }
            jpql.append(" ) ");
            List list = em.createQuery(jpql.toString()).getResultList();
            if (ListUtil.isNotEmpty(list))
            {
                b = true;
            }
        }
        return b;
    }


    @SuppressWarnings({ "rawtypes", "unchecked" })
    public List<Long> findEntityIdByRoleIds(List deptIds) throws Hl7Exception
    {
        if (ListUtil.isEmpty(deptIds))
            return null;
        StringBuilder jbql = new StringBuilder();
        jbql.append(" select r.playerEntities.entityId from Role r ");
        jbql.append(" where");
        for (int i = 0; i < deptIds.size(); i++)
        {
            String id = (String) deptIds.get(i);
            if (i < deptIds.size() - 1)
            {
                jbql.append(" r.roleId=" + id + " or ");
            }
            else
            {
                jbql.append(" r.roleId=" + id);
            }
        }
        List<Long> entyIdList = em.createQuery(jbql.toString()).getResultList();
        return entyIdList;
    }

    @SuppressWarnings("rawtypes")
    public boolean findPersonByOrgIds(List depts) throws Hl7Exception
    {
        if (ListUtil.isEmpty(depts))
            return false;
        List<Long> entyIdList = findEntityIdByRoleIds(depts);
        boolean b = false;
        if (ListUtil.isNotEmpty(entyIdList))
        {
            StringBuilder jbql = new StringBuilder();
            jbql.append(" select r.roleId from Role r");
            jbql.append(" where r.codeEtsId='" + RoleCode.EMPLOYEE.toString() + "' and (");
            for (int i = 0; i < entyIdList.size(); i++)
            {
                Long id = (Long) entyIdList.get(i);
                if (i < entyIdList.size() - 1)
                {
                    jbql.append(" r.scoperEntities.entityId=" + id + " or ");
                }
                else
                {
                    jbql.append(" r.scoperEntities.entityId=" + id);
                }
            }
            jbql.append(" ) ");
            List list = em.createQuery(jbql.toString()).getResultList();
            if (ListUtil.isNotEmpty(list))
            {
                b = true;
            }
        }
        return b;
    }
    
    @SuppressWarnings("unchecked")
    public Role findOrgRoleByCode(String code) throws Hl7Exception
    {
        List<Role> list = em.createQuery(" select r from Role r left join r.roleIiList ii where ii.extensionTxt='" + code + "' ").getResultList();
        if (ListUtil.isNotEmpty(list))
        {
            return (Role) list.get(0);
        }
        return null;
    }
    
}
